#!/bin/bash

LOG=${SOLUM_BUILD_LOG:="/opt/stack/logs/solum_build.log"}

# TLOG, PRUN, etc. defined in common/utils
HERE=$(dirname $0)
source $HERE/../../common/utils

PRUN silent docker ps
[[ $? != 0 ]] && TLOG cannot talk to docker. && exit 1

# Check command line arguments
if [ $# -lt 4 ]; then
  TLOG Usage: $0 git_url appname project_id base_image [git_private_key]
  exit 1
fi

GIT=$1
shift
APP=$1
shift
TENANT=$1
shift
BASE_IMAGE=$1
shift
GIT_PRIVATE_KEY=$1
shift

DOCKER_REGISTRY=${DOCKER_REGISTRY:-'127.0.0.1:5042'}

if [[ -z $OS_USERNAME ]]; then
  TLOG OpenStack credentials not passed via ENV.
  [[ -f ./openrc ]] && . ./openrc
  [[ -f ~/devstack/openrc ]] && . ~/devstack/openrc
fi

APP_DIR=/opt/solum/apps/$TENANT/$APP
PRUN mkdir -p $APP_DIR
add_ssh_creds "$GIT_PRIVATE_KEY" "$APP_DIR"

[[ -d $APP_DIR/build ]] && rm -rf $APP_DIR/build
git_clone_with_retry $GIT $APP_DIR/build

remove_ssh_creds "$GIT_PRIVATE_KEY"

TLOG "===>" Building App
cd $APP_DIR/build

PRUN sudo docker build -t $DOCKER_REGISTRY/$APP .

PRUN sudo docker push $DOCKER_REGISTRY/$APP
sudo docker save "$DOCKER_REGISTRY/$APP" | glance image-create --container-format=docker --disk-format=raw --name "$APP" > /dev/null

image_id=$(glance image-show $APP | grep " id " | cut -d"|" -f3 | tr -d " ")

TLOG created_image_id=$image_id

# Need stdout for solum-worker to parse the image_id
echo created_image_id=$image_id

exit 0
